package com.ruoyi.common.minio.server.impl;


import com.ruoyi.common.minio.server.MinioService;
import com.ruoyi.common.minio.util.MinioUtil;
import com.ruoyi.common.minio.util.SnowFlakeIdWorker;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Map;

@Service
@Slf4j
public class MinioServiceImpl implements MinioService {

    @Autowired
    @Qualifier("customMinioUtil")  // 指定Bean名称
    private MinioUtil minioUtil;

    @Value("${minio.bucket-name}")
    private String bucketName;

    // 雪花算法生成唯一文件名
    private SnowFlakeIdWorker worker = new SnowFlakeIdWorker(1, 1);

    @Override
    public InputStream getFile(String bucketName, String fileName) throws Exception {
        return minioUtil.getFileInputStream(fileName, bucketName);
    }

    @Override
    @SneakyThrows
    public Map<String, String> uploadFile(MultipartFile file, @NotNull String fileName){
        // 考虑更换存储桶情况
        minioUtil.bucketExists(bucketName);
        // 生成上传文件名
        String[] split = fileName.split("\\.");
        String mIniFileName = String.valueOf(worker.nextId())+"."+split[split.length-1];
        //上传文件
        return minioUtil.minioUpload(file, mIniFileName, bucketName);
    }


    @Override
    public boolean deleteFile(String bucketName,String fileName) {
        if (minioUtil.deleteFile(bucketName,fileName)){
            return true;
        }
        return false;
    }


    @Override
    public boolean saveContent(String bucketName, String fileName, String content) {
        return minioUtil.saveContent(bucketName, fileName, content);
    }

}